import os, sys, pygame, pygame.font, pygame.image

class FXSurface ( object ):
	def __init__ ( self, surf = None ):
		self._surf = surf

	def blur ( self, amount = 1.5, iterations = 5 ):
		surface = self._surf

		scale = 1.0 / float ( amount )

		surf_size = surface.get_size ()
		scale_size = ( int ( surf_size [ 0 ] * scale ), int ( surf_size [ 1 ] * scale ) )

		print surf_size, " - ", scale_size

		iters = 0
		while iters < iterations:
			surf = pygame.transform.smoothscale ( surface, scale_size )
			surface = pygame.transform.smoothscale ( surf, surf_size )
			iters += 1

		self._surf = surface

	def text ( self, txt, antialias = 1, color = ( 0, 0, 0 ), font_name = None, font_size = 60, effects = None ):
		if not effects: effects = {}

		font = pygame.font.Font ( font_name, font_size )

		img_outline = False

		if "outline" in effects:
			img_outline = self._txt_outline ( txt, font, effects )


		base = font.render ( txt, antialias, color )
		size = ( base.get_width () + 5, base.get_height () )

		img = pygame.Surface ( size, pygame.SRCALPHA )
		img.blit ( base, ( 0, 0 ), special_flags = pygame.BLEND_RGBA_ADD )

		if img_outline:
			outline = effects.get ( "outline", 0 )
			img_outline.blit ( img, ( outline, outline ) ) 
			img = img_outline

		self._surf = img

	def _txt_outline ( self, txt, font, effects ):
		outline = effects.get ( "outline", 0 )

		img_outline = False
		if outline:
			outline_color = tuple ( effects.get ( "outline_color", ( 0, 0, 0 ) ) )
			outl = font.render ( txt, 1, outline_color )
			size = ( outl.get_width () + ( outline * 2 ), outl.get_height () + ( outline * 2 ) )

			img_outline = pygame.Surface ( size, pygame.SRCALPHA )

			x = 0
			y = 0
			vals = outline * 2
			while x < vals:
				y = 0
				while y < vals:
					img_outline.blit ( outl, ( x, y ) ) 
					y += 1

				x += 1

		return img_outline

	def get ( self ):
		return self._surf

if __name__ == '__main__':
	pygame.init()

	#create our fancy text
	white = 255, 255, 255
	grey = 100, 100, 100

	surf = FXSurface ()

	surf.text ( "Hello World", effects = {
		"outline" : 4,
		"outline_color" : ( 255, 255, 0 )
	}, color = white )
	surf.blur ( 1.5 )

	text = surf.get ()

	#create a window the correct size
	w, h = text.get_size ()
	win = pygame.display.set_mode( ( w + 10, h ) )
	winrect = win.get_rect()
	win.blit  ( text, ( 0, 0 ) )
	pygame.display.flip()
	
	#wait for the finish
	while 1:
	    event = pygame.event.wait()
	    if event.type in ( pygame.event.KEYDOWN, pygame.event.MOUSEBUTTONDOWN):
	        break
	
